__author__ = 'Linson'
from numpy import *
import operator

# k-近邻算法
def create_data_set():
    group=array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1],[1.1,1.2]])
    labels=['A','A','B','B','A']
    return group ,labels

def classify(inX,dataSet,labels,k):
    dataSetSize=dataSet.shape[0]
    diffMat=tile(inX,(dataSetSize,1))-dataSet
    sqDiffMat=diffMat**2
    sqDistances=sqDiffMat.sum(axis=1)
    distances=sqDistances**0.5
    print(distances)
    sortedDistIndicies=distances.argsort() # argsort 返回数组值从小到大的索引值
    print(sortedDistIndicies)
    classCount={}
    for i in range(k):
        voteIlabel=labels[sortedDistIndicies[i]]
        classCount[voteIlabel]=classCount.get(voteIlabel,0)+1

    sortedClassCount=sorted(classCount.items(),key=operator.itemgetter(1),reverse=True)
    print(sortedClassCount)
    return sortedClassCount[0][0]

group,labels=create_data_set()
print(classify([0.8,1],group,labels,2))
print(classify([1.0,1],group,labels,2))